package task

import (
	"iot_gateway/internal/service"
	"iot_gateway/models"
	"time"
)

// type BroadcastMessage models.BroadcastMessage
type LocalBroadcastMessage struct {
	*models.BroadcastMessage
}

func NewLocalBroadcastMessage(origin *models.BroadcastMessage) *LocalBroadcastMessage {
	return &LocalBroadcastMessage{
		BroadcastMessage: origin,
	}
}

func (lb *LocalBroadcastMessage) StartDeviceMonitor() {
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		currentData := service.GetDeviceStatusFromDB()

		// 广播给所有连接的客户端
		lb.Lock.Lock()
		for client := range lb.Clients {
			if err := client.WriteJSON(currentData); err != nil {
				// 发送失败，移除客户端
				delete(lb.Clients, client)
				client.Close()
			}
		}
		lb.Lock.Unlock()
	}
}
